<!--
* description: 门店销售计划制定时机设置
* author: duanhy
* createdDate: 2020-11-18
-->
<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="apiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="false"
      :dynamic-is-show-select="true"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
    />
    <Edit
      :key="editPopupsKey"
      :is-dialog-visible="editPopupsVisible"
      :data-for-form="editRowData"
      :popups-state="editPopupsState"
      :title-name="titleName"
      @close="close"
      @save="save"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import Vue from 'vue'
import api from '@/api/apiVeData'
import commData from '@/views/ve/planReport/common/index.js'

export default {
  name: 'MonthlySalesPlan',
  components: {
    OneTableTemplate,
    Edit
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      }
    )
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '',
      lists: [],
      all: [],
      selection: '',
      row: '',
      editPopupsVisible: false,
      refreshTableKey: '0',
      // table表格查询API配置对象
      apiConfig: api.queryStoreSalePlan,
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          : [
            ...commData.ModelOptions(2),
            {
              compKey: 'compKey1',
              labelName: '制定月份：',
              codeField: 'makingMonth',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'month',
              isMust: false,
              span: 6
            },
            {
              compKey: 'compKey5',
              labelName: '计划月份：',
              codeField: 'planMonth',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'month',
              isMust: false,
              span: 6
            },
            {
              compKey: 'compKey8',
              labelName: '门店名称：',
              codeField: 'dlrShortName',
              disabled: null,
              readonly: false,
              component: () => import('./plan/index'),
              type: 'inputText',
              isMust: false,
              span: 6
            }
          ],
      // form 的表单对象
      formField:
      {
        makingMonth: '',
        planMonth: '',
        dlrShortName: '',
        dlrCode: '',
        carSeriesId: '',
        carConfigId: '',
        carColorId: '',
        carIncolorId: '',
        optionalPagId: ''
      },
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.queryTable(1),
              text: '查询'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              name: 'reset',
              clickEvent: () => this.reset(),
              text: '重置'
            },
            {
              compKey: 'btnKey3',
              type: '',
              size: 'small',
              name: '',
              position: 'left',
              isShow: false,
              clickEvent: () => this.setUp(),
              text: '设置'
            },
            {
              compKey: 'btnKey5',
              type: '',
              size: 'small',
              name: '',
              position: 'left',
              isShow: false,
              parentFileds: 'disabled:table',
              clickEvent: () => this.same(2),
              disabled: true,
              text: '发布'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols: [
        {
          prop: 'proportionSetId',
          label: 'id',
          hidden: true,
          alwaysHidden: true
        },
        {
          label: '操作',
          minWidth: 180,
          fixed: true,
          isComponent: true,
          comps: [
            {
              compKey: 'propKey1',
              labelName: '编辑',
              component: () => import('@/components/org/linkButton'),
              clickEvent: (index) => this.edit(index)
            }
          ]
        },
        {
          prop: 'dlrCode',
          label: '门店编码'
        },
        {
          prop: 'dlrShortName',
          label: '门店名称'
        },
        {
          prop: 'planStatus',
          label: '计划状态'
        },
        {
          prop: 'makingMonth',
          label: '制定月份'
        },
        {
          prop: 'endDate',
          label: '制定截止日期'
        },
        {
          prop: 'ttCode',
          label: '22位码'
        },
        {
          prop: 'planMonth',
          label: '计划月份'
        },
        {
          prop: 'carSeriesCode',
          label: '车系编码'
        },
        {
          prop: 'carSeriesCn',
          label: '车系名称'
        },
        {
          prop: 'carConfigCode',
          label: '车型编码'
        },
        {
          prop: 'carConfigCn',
          label: '车型名称'
        },
        {
          prop: 'optionalPagCode',
          label: '选装包编码'
        },
        {
          prop: 'optionalPagName',
          label: '选装包名称'
        },
        {
          prop: 'carColorCode',
          label: '车身颜色编码'
        },
        {
          prop: 'carColorName',
          label: '车身颜色名称'
        },
        {
          prop: 'carIncolorCode',
          label: '内饰颜色编码'
        },
        {
          prop: 'carIncolorName',
          label: '内饰颜色名称'
        },
        {
          prop: 'baseNum',
          label: '基数'
        },
        {
          prop: 'floatingCeiling',
          label: '浮动上限(%)'
        },
        {
          prop: 'floatingFloor',
          label: '浮动下限(%)'
        },
        {
          prop: 'creator',
          label: '创建者'
        },
        {
          prop: 'createdDate',
          label: '创建时间'
        },
        {
          prop: 'publishTime',
          label: '发布时间'
        }

      ],

      // 单表格模版页面组件回调事件
      callbackObj: {
        onAfterReset: (f, b) => {
          if (this.$store.getters.orgInfo.DLR_ID !== 'HOST') {
            this.formField.dlrShortName = this.$store.getters.orgInfo.DLR_NAME
          }
        },
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.handleSelectionChange(selection)
          this.all = selection
        }
      }
    }
  },
  mounted() {
    if (this.$store.getters.orgInfo.DLR_ID === 'HOST') {
      this.dynamicButtons.forEach(item => {
        if (item.isShow === false) {
          item.isShow = true
        }
      })
    } else {
      this.formField.dlrShortName = this.$store.getters.orgInfo.DLR_NAME
      this.tableComponents.forEach(item => {
        if (item.disabled === null) {
          item.disabled = true
          item.readonly = true
        }
      })
    }
    this.queryTable(1)
    setTimeout(() => {
      this.lists = this.$refs.multipleTable.list
    }, 1000)
  },
  methods: {
    // getSelectable(row, index) {
    //   if (row.planStatus !== '已发布' && (!row.baseNum && !row.floatingCeiling && !row.floatingFloor)) {
    //     return true
    //   }
    // },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined && o.parentFileds.indexOf('disabled:table') > -1)
      var isFloor = false
      if (selection && selection.length > 0) {
        isFloor = selection.every(item => {
          return item.baseNum && item.floatingCeiling && item.floatingFloor
        })
      }
      const isCheck = selection && selection.length > 0 && isFloor
      if (isCheck) {
        btns[0].disabled = !isCheck
        for (const k in selection) {
          if (selection[k].planStatus.includes('已发布')) {
            btns[0].disabled = isCheck
          }
        }
      } else {
        btns[0].disabled = true
      }
    },
    setUp() {
      // this.editPopupsVisible = true
      // this.titleName = '时机设置'
      this.add()
    },
    close() {
      this.editPopupsVisible = false
    },

    // 同步
    same(type) {
      // 发布
      if (type === 2) {
        const proportionSetId = []
        const updateControlId = []
        for (const k in this.all) {
          if (!this.all[k].floatingCeiling$ && !this.all[k].floatingFloor) {
            this.$message({ message: `请选择有浮动上下限的数据` })
          } else {
            proportionSetId.push(this.all[k].proportionSetId)
            updateControlId.push(this.all[k].updateControlId)
          }
        }
        var datalist1 = {
          proportionSetId: proportionSetId,
          updateControlId: updateControlId
        }
        this.car(datalist1, api.updateStoreSalePlanIssue)
      }
    },
    car(data, url) {
      const that = this
      // // 先读取参数中的传输对象
      const returnObj = {
      // api配置
        apiConfig: url,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: data
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 2000
            })
          }
          return
        } else {
        // 返回json
          this.$message({ message: response.msg, duration: 2000 })
          setTimeout(() => {
            that.queryTable(1)
            that.$refs.multipleTable.$refs.multipleTable.clearSelection()
          }, 2000)
        }
      }).catch(err => {
        console.info(err)
      })
    },

    // edit的保存
    save(formField) {
      var saveUrl
      console.log(formField.isEdit !== '')
      if (formField.isEdit !== '') {
        saveUrl = api.editSetDate
      } else {
        saveUrl = api.addStoreSalePlan
      }
      // // 先读取参数中的传输对象
      const returnObj = {
      // api配置
        apiConfig: saveUrl,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        this.$refs['multipleTable'].listLoading = false
        this.$message({ message: response.msg, type: 'success', uration: 2000 })
        this.$children[1].saveloading = false
        this.close()
        this.queryTable(1)
      }).catch(err => {
        this.$children[1].saveloading = false
        console.info(err)
      })
    }
  }
}
</script>

